//
//  MJ_ReportViewController.m
//  UEAssistant
//
//  Created by mac on 2018/1/5.
//  Copyright © 2018年 youyixinxi. All rights reserved.
//

#import "MJ_ReportViewController.h"
#import "UIColor+Extend.h"
#import "MJ_OperationViewModel.h"
#import "MJ_ReportTableViewCell.h"
#import "MJ_ReportOpenTableViewCell.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "MJ_ReportHeadView.h"
#import "MJ_CalendarView.h"
@interface MJ_ReportViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
MJ_ReportHeadViewDelegate,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate,
MJReportCellDelegate
>

@property (strong, nonatomic)UITableView *tableView;

@property (strong, nonatomic)MJ_OperationViewModel *viewModel;
/**tableView选择打开的组下标*/
@property (assign, nonatomic)NSInteger openSectionIndex;

@property (strong, nonatomic)MJ_ReportHeadView *headView;

@end

@implementation MJ_ReportViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64-44) style:UITableViewStylePlain];
        [_tableView registerClass:[MJ_ReportTableViewCell class] forCellReuseIdentifier:@"MJ_ReportTableViewCell"];
        [_tableView registerClass:[MJ_ReportOpenTableViewCell class] forCellReuseIdentifier:@"MJ_ReportOpenTableViewCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor colorWithHexString:@"#e0e0e0"];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
    }
    return _tableView;
}
- (MJ_ReportHeadView *)headView {
    if (!_headView) {
        _headView = [[[NSBundle mainBundle] loadNibNamed:@"MJ_ReportHeadView" owner:nil options:nil] lastObject];
        _headView.frame = CGRectMake(0, 0, Screen_Width, 134);
        _headView.backgroundColor = [UIColor whiteColor];
        _headView.delegate = self;
    }
    return _headView;
}

- (MJ_OperationViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[MJ_OperationViewModel alloc] init];
    }
    return _viewModel;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _openSectionIndex = -1;
    [self loadDataWithParameter:[self calulateTimeWithType:MJTimeSelectTypeToday]];
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headView;

}

- (void)loadDataWithParameter:(NSDictionary *)parameter{
    
    [LSProgressHUD showLoadingToView:self.navigationController.view];

    __weak typeof(self) wSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameter];
    [dic setObject:shareData.userId forKey:@"owner_id"];
    [self.viewModel loadProductReportListWithParameter:dic success:^(BOOL success) {
        __strong typeof(wSelf) sSelf = wSelf;
        if (success) {
            [sSelf.tableView reloadData];
            //改变起始button的显示
            NSString *start = parameter[@"begintime"];
            NSString *end = parameter[@"endtime"];
            NSDateFormatter *f = [[NSDateFormatter alloc] init];
            f.dateFormat = @"yyyy-MM-dd";
            NSDate *startDate = [f dateFromString:start];
            NSDate *endDate = [f dateFromString:end];
            //改变headButton的值
            [sSelf.headView changeButtonTitleWithBeginDate:startDate endDate:endDate];
        }
        [LSProgressHUD hideForView:self.navigationController.view];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.reportList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_openSectionIndex == section) {
        return 2;
    }else{
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        MJ_ReportTableViewCell *listCell = [tableView dequeueReusableCellWithIdentifier:@"MJ_ReportTableViewCell" forIndexPath:indexPath];
        listCell.delegate = self;
        listCell.model = self.viewModel.reportList[indexPath.section];
        return listCell;
    }else{
        MJ_ReportOpenTableViewCell *openCell = [tableView dequeueReusableCellWithIdentifier:@"MJ_ReportOpenTableViewCell" forIndexPath:indexPath];
        openCell.openModel = self.viewModel.reportList[indexPath.section];
        return openCell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        return 101;
    }else{
        return 70;
    }
}

//点击下拉展开或者收起
- (void)clickOpenWithCell:(MJ_ReportTableViewCell *)cell{

    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSInteger numberOfRows = [self.tableView numberOfRowsInSection:indexPath.section];
    if (numberOfRows == 1) {
        _openSectionIndex = indexPath.section;
    }else{
        _openSectionIndex = -1;
    }
    [self.tableView reloadData];
}

//点击head选择日期
- (void)clickWithType:(MJTimeSelectType)type button:(UIButton *)button view:(MJ_ReportHeadView *)view {
    if (type == MJTimeSelectTypeStart) {
        MJ_CalendarView *calendarView = [[MJ_CalendarView alloc] initWithFrame:CGRectMake(0, Screen_Height/5, Screen_Width, Screen_Height/5*4)];
        calendarView.isStartDate = YES;
        __weak typeof(self) wSelf = self;
        calendarView.SelectDateBlock = ^(NSDate *startDate, NSDate *endDate) {
            
            __strong typeof(wSelf) sSelf = wSelf;
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd";
            TGLog(@"开始时间 = %@, 结束时间 = %@",[formatter stringFromDate:startDate],[formatter stringFromDate:endDate]);
            [sSelf loadDataWithParameter:@{@"begintime":[formatter stringFromDate:startDate],@"endtime":[formatter stringFromDate:endDate]}];
            formatter.dateFormat = @"MM-dd";
            sSelf.headView.isSelectRange = YES;
        };
        [calendarView openCalendar];
        
    }else if (type == MJTimeSelectTypeEnd) {
        
        __weak typeof(self) wSelf = self;
        MJ_CalendarView *calendarView = [[MJ_CalendarView alloc] initWithFrame:CGRectMake(0, Screen_Height/5, Screen_Width, Screen_Height/5*4)];
        calendarView.isStartDate = NO;
        calendarView.SelectDateBlock = ^(NSDate *startDate, NSDate *endDate) {
            
            __strong typeof(wSelf) sSelf = wSelf;
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd";
            TGLog(@"开始时间 = %@, 结束时间 = %@",[formatter stringFromDate:startDate],[formatter stringFromDate:endDate]);
            [sSelf loadDataWithParameter:@{@"begintime":[formatter stringFromDate:startDate],@"endtime":[formatter stringFromDate:endDate]}];
            sSelf.headView.isSelectRange = YES;
        };
        [calendarView openCalendar];
        
    }else{
        NSDictionary *dic = [self calulateTimeWithType:type];
        [self loadDataWithParameter:dic];
    }

}

- (NSDictionary *)calulateTimeWithType:(MJTimeSelectType)type {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:[[NSDate alloc] init]];
    
    [components setHour:-[components hour]];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    //今天
    NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);
    switch (type) {
        case MJTimeSelectTypeToday:
        {
            TGLog(@"今天 = %@",[formatter stringFromDate:today]);
            return @{@"begintime":[formatter stringFromDate:today],@"endtime":[formatter stringFromDate:today]};
        }
            
        case MJTimeSelectTypeYesterday:
        {
            //昨天
            [components setHour:-24];
            [components setMinute:0];
            [components setSecond:0];
            NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
            TGLog(@"昨天 = %@",[formatter stringFromDate:yesterday]);
            return @{@"begintime":[formatter stringFromDate:yesterday],@"endtime":[formatter stringFromDate:yesterday]};
        }
            
        case MJTimeSelectTypeTheDayBeforeYesterday:
        {
            //前天
            [components setHour:-48];
            [components setMinute:0];
            [components setSecond:0];
            NSDate *theDayBeforeYesterday  = [cal dateByAddingComponents:components toDate: today options:0];
            TGLog(@"前天 = %@",[formatter stringFromDate:theDayBeforeYesterday]);
            return @{@"begintime":[formatter stringFromDate:theDayBeforeYesterday],@"endtime":[formatter stringFromDate:theDayBeforeYesterday]};
        }
        case MJTimeSelectTypeWeek:
        {
            components = [cal components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[[NSDate alloc] init]];
            [components setDay:([components day] - ([components weekday] - 2))];
            NSDate *thisWeek  = [cal dateFromComponents:components];
            TGLog(@"本周 = %@ ~ %@",[formatter stringFromDate:thisWeek],[formatter stringFromDate:today]);
            return @{@"begintime":[formatter stringFromDate:thisWeek],@"endtime":[formatter stringFromDate:today]};

        }
        case MJTimeSelectTypeMonth:
        {
            components = [cal components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[[NSDate alloc] init]];
            [components setDay:([components day] - ([components day] -1))];
            NSDate *thisMonth = [cal dateFromComponents:components];
            TGLog(@"本月 = %@ ~ %@",[formatter stringFromDate:thisMonth],[formatter stringFromDate:today]);
            return @{@"begintime":[formatter stringFromDate:thisMonth],@"endtime":[formatter stringFromDate:today]};

        }
        default:
            return @{};
    }
}


#pragma mark --空数据处理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"任务"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = @"空空如也~";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0f],
                                 NSForegroundColorAttributeName: [UIColor darkGrayColor]};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    
    return YES;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    
    return 30;
}

@end
